package com.jinxin.platform.cdsmsmgr.utils;

import com.jinxin.platform.cdsmsmgr.redis.RedisUtil;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @author: 金鑫智慧
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 * @Date: 2019/6/13
 * @Author: lingnan
 **/
@Component
public class ShortMessageUtil {
    @Autowired
    private RedisUtil redisUtil;

    private RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }

    /**
     * 异步发送短信
     *
     * @param code  验证码 -- 5位数字
     * @param phone 电话号码 -- 11位
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws KeyManagementException
     */
    @Async
    public void sendShortMessage(Integer code, String phone)
            throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        String requestUrl = "https://cdcxdxjk.market.alicloudapi.com/chuangxin/dxjk?content=【APCOS开发者】你的注册验证码是：" + code + "，3分钟内有效！&mobile=" + phone;
        ResponseEntity<String> response = sendMsgCore(requestUrl);
        if (response.getStatusCode().value() == 200) {
            //发送完成以后就设置缓存--3分钟--180秒
            redisUtil.set(phone.replaceAll(" ", ""), code, 180L);
        }
    }
    @Async
    public void sendShortMessage2(Integer code, String phone)
            throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        String requestUrl = "https://cdcxdxjk.market.alicloudapi.com/chuangxin/dxjk?content=【APCOS开发者】验证码：" + code + "，3分钟内有效！&mobile=" + phone;
        ResponseEntity<String> response = sendMsgCore(requestUrl);
        if (response.getStatusCode().value() == 200) {
            //发送完成以后就设置缓存--3分钟--180秒
            redisUtil.set(phone.replaceAll(" ", "")+"_reset_pwd", code, 180L);
        }
    }

    ResponseEntity<String> sendMsgCore(String requestUrl) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        String appcode = "9409783607ba4c50aa7e81475bc6ca3e";
        // 模块是固定的,不能修改
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        header.set("Authorization", "APPCODE " + appcode);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(header);
        return restTemplate().postForEntity(requestUrl, request, String.class);
    }

}
